/**
 * 
 */
package com.edocbase.desktop.swt.widgets;

import java.io.File;

import org.eclipse.jface.viewers.TreeNode;

/**
 * @author lifei114@gmail.com
 *
 */
public class FileNode extends TreeNode {
	private String displayName = null;
	File file = null;
	private File[] files = null;
	public FileNode(File file) {
		super(file);
		this.file = file;
	}
	@Override
	public FileNode getParent() {
		if (file.getParentFile() == null){
			return null;
		}else{
			return new FileNode(file.getParentFile());
		}
	}
	@Override
	public File getValue() {
		return (File) super.getValue();
	}
	@Override
	public boolean hasChildren() {
		if (file.isFile()){
			return false;
		}else if (file.isDirectory()){
			//return getChildCount()>0;
			return true;
		}
		return false;
	}
	public int getChildCount(){
		FileNode[] children = getChildren();
		if (children == null){
			return 0;
		}
		return children.length;
	}
	@Override
	public FileNode[] getChildren() {
		fetchFiles();
		return (FileNode[]) super.getChildren();
	}
	private void fetchFiles(){
		fetchFiles(false);
	}
	public void fetchFiles(boolean refresh){
		if (refresh || files == null){
			files = file.listFiles();
			if (files == null){
				files = new File[0];
			}
			FileNode[] nodes = new FileNode[files.length];
			for (int i=0;i<files.length;i++){
				File file = files[i];
//				if (file == null){
//					continue;
//				}
				nodes[i] = new FileNode(file);
			}
			setChildren(nodes);
		}
	}
	public boolean isRoot(){
		return file.getParentFile()==null;
	}
	
	public boolean isDriver() {
		File file = getValue();
		return file.isDirectory() && file.getParentFile() == null
				&& file.isAbsolute();
	}
	public String getDisplayName() {
		if (displayName == null){
			if (isDriver()){
				File file = getValue();
				displayName = file.getPath();
			}else{
				File file = getValue();
				displayName = file.getName();
				if (displayName.length() == 0){
					displayName = file.getPath();
				}
			}
		}
		return displayName;
	}

	public void setDisplayName(String displayName) {
		this.displayName = displayName;
	}
	@Override
	public String toString() {
		return "FileNode [file=" + file + "]";
	}
	public FileNode getChildNode(int index) {
		FileNode[] children = getChildren();
		if (children == null){
			return null;
		}
		if (index >= children.length){
			return null;
		}
		return children[index];
	}
	
}
